/* ==================================== 全局变量 开始*/
let global_content = ["title", "content", "descript"];
let i, j, k = 0;
let languages_zh = ["英式英语", "法语", "德语", "意大利", "西班牙", "美式英语", "荷兰", "瑞典", "波兰",];
let languages = ["en", "fr", "de", "it", "es", "us", "nl", "sv", "pl"];
let tags = [1, 2, 3, 4, 5, 9, 10, 11, 12];
let cont = ["title", "content", "descript"];
let cont_zh = ["标题", "五点", "描述"];
let v = [1, 3, 4];
const emoji = "◍";
// const emoji = "❤";
/* ==================================== 全局变量 结束*/

/* ==================================== 全局方法 开始*/
// ----------------------------------
// --- 消息提示
function msgTip(msg, icon, time) {
    const script = document.createElement("script");
    script.textContent =
        `
        (function() {
                layer.msg("` +
        msg +
        `", {anim: 0,offset:'auto',time: ` +
        time +
        `});
        })();
    `;
    document.head.appendChild(script);
    document.head.removeChild(script);
}

// ----------------------------------
// --- 获取URL参数
function getUrlParam(name) {
    return new URLSearchParams(window.location.search).get(name);
}

// ----------------------------------
// --- 语言英文转中文
const getLanguageName = (langCode) => {
    const languageMap = {
        en: "英式英语",
        fr: "法语",
        de: "德语",
        it: "意大利语",
        es: "西班牙语",
        us: "美式英语",
        nl: "荷兰语",
        sv: "瑞典语",
        pl: "波兰语",
    };
    return languageMap[(langCode || "").toLowerCase()] || "未知语言";
};
// ----------------------------------
// --- 点击计算价格
function clickComputePrice() {
    // $("a:contains('计算价格')").click();
    $("a:contains('计算价格')").trigger("click");
    dhtmlx.message("【计算价格】执行完成！");
}

// ----------------------------------
/* ==================================== 全局方法 结束*/
// ----------------------------------

// --- 修改标签页标题

let tabTitle = $("input[name='lc_sku']").val();
// let tabTitle = $("input[name='lc_sku']").val() + '&' + getUrlParam('id')
document.querySelector("head > title").textContent = tabTitle.length > 0 ? tabTitle : "未提交";

// ----------------------------------
// ---顶部和底部按钮
const c = (t, s, h) =>
    $("<div>")
        .css({
            width: "30px",
            lineHeight: "50px",
            textAlign: "center",
            position: "fixed",
            fontWeight: "bold",
            cursor: "pointer",
            left: "0",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            ...s,
        })
        .text(t)
        .click(h)
        .appendTo("body");
c(
    "👆",
    {
        height: "40%",
        top: "0",
        borderBottom: "1px solid #716e6e",
    },
    () =>
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        })
);
c(
    "💵",
    {
        height: "20%",
        top: "40%",
    },
    () => {
        $(
            "body > div.x-body > div > form > div > hr:nth-child(11)"
        )[0]?.scrollIntoView({
            behavior: "smooth",
            block: "start",
        });
    }
);
c(
    "👇",
    {
        height: "40%",
        top: "60%",
        borderTop: "1px solid #716e6e",
    },
    () =>
        window.scrollTo({
            top: 5e3,
            behavior: "smooth",
        })
);

// ----------------------------------
// ---添加更新SKU并提交按钮
$("input[value*='本地化图片链接']").after(
    $(
        '<input type="button" style="margin-left:10px;background-color: #a6a646;" class="duotu_upload layui-btn " value="更新SKU并提交">'
    ).click(function () {
        $("input[name='lc_sku']").val("");
        $(".layui-btn.b1.fl").click();
    })
);
// ----------------------------------
// ---修改产品图片样式
$(".wdcpadd .cpad1 .a2 .b2").css({width: "90%",});
$(".photo_upload_box").css({width: "100%",});
// ----------------------------------
// ---填入品牌
$("input[name='brand']").val(1);
// ----------------------------------

// ----------------------------------
// --- 隐藏无关国家的运费

// --- 修改运费表格
const shippingFeeTable = document.querySelector("#yunfei");
if (shippingFeeTable) {
    // 创建容器
    const shippingFeeContainer = document.createElement("div");
    shippingFeeContainer.id = "shipping-fee-container";
    Object.assign(shippingFeeContainer.style, {
        display: "flex",
        gap: "30px",
        alignItems: "flex-start",
    });

    // 插入容器
    shippingFeeTable.parentNode.insertBefore(
        shippingFeeContainer,
        shippingFeeTable
    );
    shippingFeeContainer.appendChild(shippingFeeTable);

    // 新表格模板
    const newTableHTML = `
    <table id="insert-variant-price-table" class="layui-table" style="width:auto;margin-top: 10px;">
        <thead>
            <tr>
                <th>国家</th>
                <th>售价</th>
                <th><a id="exchange_rate_price" class="layui-btn layui-btn-xs layui-bg-blue calculate-all">计算</a></th>
                <th>汇率</th>
                <th><a id="insert_rate_price" class="layui-btn layui-btn-xs layui-bg-blue insert-all">插入</a></th>
            </tr>
        </thead>
        <tbody class="shipping-fee-tbody">
        </tbody>
    </table>`;

    // 插入新表格
    shippingFeeContainer.insertAdjacentHTML("beforeend", newTableHTML);

    // 初始化功能
    const STORAGE_KEY = "country_rates";
    let countryRateMap = {};

    // 从原表获取国家列表
    function getCountries() {
        const countries = [];
        document.querySelectorAll("#yunfei tbody tr").forEach((row) => {
            const countryTd = row.querySelector("td:nth-child(2)");
            const country = countryTd.textContent.replace(/\s+/g, " ").trim();
            if (!countries.includes(country)) {
                countries.push(country);
            }
        });
        // console.log(countries);
        return countries;
    }

    // 初始化本地存储
    function initStorage() {
        const stored = localStorage.getItem(STORAGE_KEY);
        countryRateMap = stored ? JSON.parse(stored) : {};

        // 合并新国家到存储
        getCountries().forEach((country) => {
            if (!(country in countryRateMap)) {
                countryRateMap[country] = "";
            }
        });
        localStorage.setItem(STORAGE_KEY, JSON.stringify(countryRateMap));
    }

    /**
     * 从API获取最新汇率并更新本地存储
     * @returns {Promise<void>}
     */
    async function updateExchangeRates() {
        try {
            // 获取本地存储的汇率数据
            const localRates =
                JSON.parse(localStorage.getItem("country_rates")) || {};

            // 发送GET请求获取最新汇率
            const response = await fetch(
                "https://api.exchangerate-api.com/v4/latest/CNY"
            );
            if (!response.ok)
                throw new Error(`HTTP error! status: ${response.status}`);

            const data = await response.json();
            console.log("exchangerate-API返回CNY汇率数据:", data);

            // 转换API数据格式 {国家 代码: 汇率}
            const updatedRates = {};
            for (const [countryCode, rate] of Object.entries(localRates)) {
                const currencyCode = countryCode.split(" ")[1]; // 从"美国 USD"提取USD
                if (data.rates[currencyCode]) {
                    // updatedRates[countryCode] = (1 / data.rates[currencyCode]).toFixed(4);
                    updatedRates[countryCode] = data.rates[currencyCode];
                } else {
                    updatedRates[countryCode] = rate; // 保留API未提供的货币
                }
            }

            // 存储更新后的数据
            localStorage.setItem("country_rates", JSON.stringify(updatedRates));
            console.log("汇率更新完成，最后更新时间:", data.date);
        } catch (error) {
            console.error("汇率更新失败:", error);
            throw error;
        }
    }

    // 更新汇率并打印
    updateExchangeRates().then(() => {
        console.log("最新汇率:", JSON.parse(localStorage.getItem("country_rates")));
    });

    // 创建表格行
    function createRows() {
        const tbody = document.querySelector("#insert-variant-price-table tbody");
        tbody.innerHTML = "";

        getCountries().forEach((country) => {
            const rate = countryRateMap[country] || "";
            const row = document.createElement("tr");
            row.innerHTML = `
                <td>${country}</td>
                <td colspan="2">
                    <input type="number" 
                           class="price-input" 
                           style="width:100px;padding:5px 10px;border:1px solid #e6e6e6;">
                </td>
                <td colspan="2">
                    <input type="number" 
                           class="rate-input" 
                           value="${rate}"
                           style="width:100px;padding:5px 10px;border:1px solid #e6e6e6;">
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    // 事件处理
    $(document).on("click", function (e) {
        const $target = $(e.target);

        // 全部计算
        if ($target.hasClass("calculate-all")) {
            const rmbValue = parseFloat($("#default_price").val());
            if (isNaN(rmbValue)) return;

            $("#insert-variant-price-table tbody tr").each(function () {
                const $row = $(this);
                const rateValue = parseFloat($row.find(".rate-input").val());

                if (!isNaN(rateValue)) {
                    const price = (rmbValue * rateValue).toFixed(2);
                    $row.find(".price-input").val(price);
                }
            });
        }

        // 统一处理国家名称格式
        const normalizeCountry = (str) => {
            // 替换所有空格和HTML空格实体为单个标准空格
            return str
                .replace(/\s+/g, " ")
                .replace(/&nbsp;/g, " ")
                .replace(/\u00a0/g, " ")
                .trim();
        };

        // 全部插入
        if ($target.hasClass("insert-all")) {
            $("#insert-variant-price-table tbody tr").each(function () {
                const $row = $(this);
                // 获取标准化国家名称
                const country = normalizeCountry($row.find("td:first").text());
                const price = $row.find(".price-input").val();

                $("#yunfei tbody tr").each(function () {
                    const $origRow = $(this);
                    // 标准化原表国家名称
                    const origCountry = normalizeCountry(
                        $origRow.find("td:nth-child(2)").text()
                    );

                    if (origCountry === country) {
                        $origRow.find('input[name="shoujia[]"]').val(price);
                    }
                });
            });
        }
    });

    // 汇率保存
    document.addEventListener("input", (e) => {
        if (e.target.classList.contains("rate-input")) {
            const row = e.target.closest("tr");
            const country = row.querySelector("td:first-child").textContent.trim();
            countryRateMap[country] = e.target.value;
            localStorage.setItem(STORAGE_KEY, JSON.stringify(countryRateMap));
        }
    });

    // window.onload = function () {
    //     console.log("【YiQiGouHelper】加载成功")
    setTimeout(() => {
        // 初始化本地存储
        initStorage();
        // 创建表格行
        createRows();
        // 点击计算汇率价格按钮
        $("#exchange_rate_price").click();
        // 点击插入汇率价格按钮
        if ($("#is_default").is(":checked")) $("#insert_rate_price").click();
    }, 1100);
    // }
}

// ----------------------------------

// ----------------------------------
// --- 人民币/美元/人民币 计算售价
$("body > div.x-body > div > form > div > div.clearfix.layui-form > ul").append(
    '<li class="b3 clearfix"></li>'.repeat(2)
);

// 通用输入处理器
function createCurrencyInput(config) {
    // 创建DOM元素
    const $container = $("div.clearfix.layui-form > ul > li:nth-child(5)");
    const labelClass = config.name === "人民币" ? "c1" : "c3";
    $container.append(`
        <p class="${labelClass} fl" ${config.name !== "人民币" ? 'style="width:138px;"' : ""
    }>${config.name}售价：</p>
        <input type="text" class="c4 fl price2" id="${config.id}"placeholder="${config.placeholder
    }">
    `);
    // 绑定事件
    $(`#${config.id}`).on("input", function () {
        const hasValue = this.value.trim().length > 0;
        const cost = hasValue ? config.calc(Number(this.value)) : 100;
        $("#zhongliang").val(hasValue ? 1 : 5);
        $("#chengben").val(cost.toFixed(2));
        clickComputePrice();
    });
}

// 统一配置器
const currencyConfigs = [
    {
        name: "人民币",
        id: "rmb_jia_ge",
        placeholder: "请输入最终售价的人民币",
        calc: (val) => ((val * 0.1098) / 1.2 / 1.15) * 4.5 - 200,
    },
    {
        name: "美元",
        id: "mei_yuan_jia_ge",
        placeholder: "请输入最终售价的美元",
        calc: (val) => ((val / 1.08 / 1.15) * 6) / (5 / 3) - 200,
    },
    {
        name: "英镑",
        id: "ying_bang_jia_ge",
        placeholder: "请输入最终售价的英镑",
        calc: (val) => (val / 1.2 / 1.15) * 4.5 - 200,
    },
];
// 批量创建输入框
currencyConfigs.forEach(createCurrencyInput);
// ----------------------------------
// --- 变化后计算价格
const zhongliang = document.getElementById("zhongliang");
zhongliang.addEventListener("input", function (event) {
    const value = event.target.value; // 获取输入的值
    console.log("【重量输入】值:", value);
    dhtmlx.message("【重量输入】值:" + value);
    clickComputePrice();
});
const chengben = document.getElementById("chengben");
chengben.addEventListener("input", function (event) {
    const value = event.target.value; // 获取输入的值
    console.log("【成本输入】值:", value);
    dhtmlx.message("【成本输入】值:" + value);
    clickComputePrice();
});
// ----------------------------------
// --- 是否默认输入售价

function setDefaultPrice() {
    if (
        localStorage.getItem("default_price") > 0 &&
        localStorage.getItem("is_default") == 1
    ) {
        const value = Number(localStorage.getItem("default_price")) * 0.1098; // 获取输入的值
        let chengben = (value / 1.2 / 1.15) * 4.5 - 200;
        $("#zhongliang").val(1);
        $("#chengben").val(chengben);
    }
}


$("div.clearfix.layui-form > ul > li:nth-child(6)").append(
    $("<p/>", {
        class: "c1 fl",
        text: "默认售价：",
    }),
    $("<input/>", {
        id: "default_price",
        type: "text",
        class: "c4 fl price2",
        placeholder: "请输入默认售价的人民币",
    }),
    $("<p/>", {
        class: "c3 fl",
        style: "width:138px;",
        text: "是否默认填入：",
    }),
    $("<input/>", {
        id: "is_default",
        type: "checkbox",
        name: "layTableCheckbox",
        "lay-skin": "primary",
        "lay-filter": "layTableAllChoose",
    })
);

layui.use(["form"], function () {
    // 初始化复选框状态
    let checkbox = document.getElementById("is_default");
    let savedValue = localStorage.getItem("is_default");
    checkbox.checked = savedValue === "1";
    layui.form.render("checkbox"); // 重新渲染复选框
    // 监听复选框变化
    layui.form.on("checkbox(layTableAllChoose)", function (data) {
        if (data.elem.checked) {
            localStorage.setItem("is_default", "1");
            setDefaultPrice();
            clickComputePrice();
        } else localStorage.setItem("is_default", "0");
    });
});
layui.use(["jquery", "form"], function () {
    let $ = layui.jquery;
    let form = layui.form;
    // 从 localStorage 读取保存的值
    let savedPrice = localStorage.getItem("default_price");
    if (savedPrice !== null) {
        $("#default_price").val(savedPrice); // 设置输入框的值
        form.render(); // 重新渲染表单（确保UI更新）
    }

    // 监听输入框变化（实时保存）
    $("#default_price").on("input", function () {
        localStorage.setItem("default_price", $(this).val());
        if (
            localStorage.getItem("default_price") > 0 &&
            localStorage.getItem("is_default") === "1"
        ) {
            const value = Number(localStorage.getItem("default_price")) * 0.1098; // 获取输入的值
            let chengben = (value / 1.2 / 1.15) * 4.5 - 200;
            $("#zhongliang").val(1);
            $("#chengben").val(chengben);
            clickComputePrice();
        }
    });
});
// ----------------------------------
// --- 参考价格计算
$("a[onclick=\"jisuan('')\"], a[onclick=\"ybjisuan('')\"]").wrapAll(
    '<div id="indicative-price-container" class="indicative-price-container"></div>'
);
$("#indicative-price-container").append(
    '<a style="background-color: rgb(243 243 243);color: black;" class="layui-btn a6">参考价格增加：</a>'
);
[5, 10, 20, 30, 50, 100, 200, 300, 500].forEach((price) => {
    const $btn = $(
        '<a name="indicative-price-button" class="layui-btn a6 price-btn">+' +
        price +
        "</a>"
    ).on("click", (e) => {
        e.preventDefault();
        console.log("当前参考价格计算增加：", price);
        let cankaos = Number($("#cankaos").val());
        let chengben = ((cankaos + price) / 1.2 / 1.15) * 4.5 - 200;
        $("#zhongliang").val(1);
        $("#chengben").val(chengben);
        dhtmlx.message("【参考价格】+" + price);
        clickComputePrice();
    });
    $("#indicative-price-container").append($btn);
});

// ----------------------------------
// --- 填入变体价格
// 定位原始变体价格表格
const originalTable = document.querySelector("table.btcon.layui-table");
originalTable.id = "variant-price-table";
if (originalTable) {
    // 创建容器并设置布局
    const container = document.createElement("div");
    container.id = "variant-price-container";
    Object.assign(container.style, {
        display: "flex",
        gap: "30px",
        alignItems: "flex-start",
    });
    originalTable.parentNode.insertBefore(container, originalTable);
    container.appendChild(originalTable);
    const tbody = document.querySelector(
        "#variant-price-container > table > tbody"
    );
    //
    if (!tbody.firstElementChild) {
        msgTip("没有变体");
        console.log("没有变体");
        $('[name="lc_remark"]').val("1没有变体");
        $('[name="indicative-price-button"]').css({
            "background-color": "rgb(135 255 140 / 85%)",
            color: "black",
        });
    } else {
        msgTip("有变体");
        console.log("有变体");
        $('[name="lc_remark"]').val("1有变体");
        $('[name="indicative-price-button"]').css({
            "background-color": "rgb(255, 94, 44, 0.7)",
        });

        // 新表格模板
        const newTableHTML = `
    <table id="insert-variant-price-table" class="layui-table" style="width:auto;margin-top: 15px;">
        <thead>
            <tr>
                <th colspan="2"><a id="install-price" class="layui-btn" style="width: 100%">填入变体价格</a></th>
                <th><a class="add-row layui-btn" style="background-color: #bfa25b;">添加</a></th>
            </tr>
        </thead>
        <tbody class="dynamic-body1">
            <!-- 初始行会被本地存储数据覆盖 -->
            <tr><td><input type="text" class="layui-input variant-input" style="width: 100px"></td>
                <td><input type="number" class="layui-input price-input"></td>
                <td><a class="delete-row layui-btn layui-btn-danger">删除</a></td></tr>
        </tbody>
    </table>`;

        // 插入新表格
        container.insertAdjacentHTML("beforeend", newTableHTML);
        // 核心功能增强
        const tableBody = container.querySelector(".dynamic-body1");

        // ======== 新增本地存储功能 ========
        // 1. 数据存储函数
        const saveTableData = () => {
            const data = Array.from(tableBody.rows).map((row) => ({
                variant: row.querySelector(".variant-input").value,
                price: row.querySelector(".price-input").value,
            }));
            localStorage.setItem("tableData", JSON.stringify(data));
        };

        // 2. 数据加载函数
        const loadTableData = () => {
            const savedData = localStorage.getItem("tableData");
            if (!savedData) return;

            // 清空现有行（包括初始示例行）
            tableBody.innerHTML = "";

            JSON.parse(savedData).forEach((item) => {
                const newRow = document.createElement("tr");
                newRow.innerHTML = `
                <td><input type="text"
                      class="layui-input variant-input"
                      value="${item.variant.replace(/"/g, "&quot;")}"></td>
                <td><input type="number"
                      class="layui-input price-input"
                      value="${item.price}"></td>
                <td><a class="delete-row layui-btn layui-btn-danger">删除</a></td>`;
                tableBody.appendChild(newRow);
            });

            // 保证至少保留一行
            if (!tableBody.rows.length) addNewRow();
        };

        // 3. 实时同步机制
        container.addEventListener("input", (e) => {
            if (e.target.matches(".layui-input")) {
                saveTableData();
                e.target.style.borderColor = "#5FB878"; // 可视化反馈
                setTimeout(() => (e.target.style.borderColor = ""), 500);
            }
        });

        // ======== 修改原有事件处理 ========
        // 添加行函数（独立封装）
        const addNewRow = () => {
            const newRow = document.createElement("tr");
            newRow.innerHTML = `
            <td><input type="text" class="layui-input variant-input"></td>
            <td><input type="number" class="layui-input price-input"></td>
            <td><a class="delete-row layui-btn layui-btn-danger">删除</a></td>`;
            tableBody.appendChild(newRow);
            saveTableData(); // 新增行后立即保存
        };

        // 事件委托处理
        container.addEventListener("click", (e) => {
            // 添加行
            if (e.target.closest(".add-row")) {
                e.preventDefault();
                addNewRow();
            }

            // 删除行
            if (e.target.closest(".delete-row")) {
                e.preventDefault();
                const row = e.target.closest("tr");
                row.remove();
                saveTableData(); // 删除后立即保存

                // 保留最后一行占位
                if (!tableBody.rows.length) addNewRow();
            }
        });

        // 初始化时加载数据
        loadTableData();

        // 样式增强
        const style = document.createElement("style");
        style.textContent = `
        .layui-input:focus { box-shadow: 0 0 8px rgba(95,184,120,.3); }
        .dynamic-body1 tr:hover { background: #f8f8f8; }`;
        document.head.appendChild(style);

        // 在现有代码基础上添加以下功能
        const installPriceHandler = () => {
            // 获取新旧表数据映射
            const newDataMap = new Map();
            Array.from(tableBody.querySelectorAll("tr")).forEach((row) => {
                const variant = row.querySelector(".variant-input").value.trim();
                const price = parseFloat(row.querySelector(".price-input").value);
                if (variant) newDataMap.set(variant, price);
            });

            // 旧表遍历逻辑
            Array.from(originalTable.querySelectorAll("tbody tr")).forEach(
                (oldRow) => {
                    // 获取旧表变体名称（处理隐藏输入框）
                    const variantTd = oldRow.querySelector("td:nth-child(2)");
                    const variantName = variantTd.textContent
                        .replace(/<input[\s\S]*?>/g, "") // 移除隐藏输入框
                        .trim()
                        .replace(/\s+/g, " ");

                    // 获取价格输入框
                    const priceInput = oldRow.querySelector(
                        "td:nth-child(4) input.bt_price"
                    );

                    // 执行匹配逻辑
                    if (variantName && priceInput) {
                        const matchedPrice = newDataMap.get(variantName);
                        if (matchedPrice && !isNaN(matchedPrice)) {
                            priceInput.value = matchedPrice.toFixed(2);
                            // 触发原始事件监听
                            priceInput.dispatchEvent(
                                new Event("input", {
                                    bubbles: true,
                                })
                            );
                        }
                    }
                }
            );
            // 添加视觉反馈
            originalTable.style.transform = "scale(1.02)";
            setTimeout(() => (originalTable.style.transform = ""), 500);
        };
        // 绑定按钮事件（在loadTableData之后添加）
        document
            .getElementById("install-price")
            .addEventListener("click", function (e) {
                e.preventDefault();
                installPriceHandler();
            });

        // 添加样式增强
        const syncStyle = document.createElement("style");
        syncStyle.textContent = `
    @keyframes priceSync {
        0% { box-shadow: 0 0 10px rgba(95,184,120,0); }
        50% { box-shadow: 0 0 15px rgba(95,184,120,0.4); }
        100% { box-shadow: 0 0 10px rgba(95,184,120,0); }
    }
    .bt_price:focus {
        border-color: #5fb878 !important;
        animation: priceSync 1.5s ease-in-out;
    }`;
        document.head.appendChild(syncStyle);
    }


}
// ----------------------------------
// --- 首字大写修改样式
$("a:contains('首字大写')").removeClass("fr").addClass("layui-btn fanyis");
// ----------------------------------
// --- 确认提交按钮修改样式
$(".layui-btn.b1.fl").css({
    "background-color": "rgb(191, 162, 91, 0.7)",
    position: "fixed",
    left: "50px",
    bottom: "10px",
});
// ----------------------------------
// --- 英式英语和美式英语互填
global_content.forEach((c) =>
    $("#en" + c).val((i, v) => v || $("#us" + c).val())
);

// ----------------------------------
// --- 替换中文标点
// 定义中文标点到英文标点的映射
const chineseToEnglishPunctuationMap = {
    "，": ",",
    "。": ".",
    "？": "?",
    "！": "!",
    "：": ":",
    "；": ";",
    "‘": "'",
    "’": "'",
    "“": '"',
    "”": '"',
    "（": "(",
    "）": ")",
    "【": "[",
    "】": "]",
    "《": "<",
    "》": ">",
    "·": ".",
    "——": "--",
    "…": "...",
    "、": ",",
};
let t = ["en", "us"];
for (i = 0; i < t.length; i++) {
    for (j = 0; j < global_content.length; j++) {
        let text = $("#" + t[i] + global_content[j]).val();
        // 遍历映射对象，使用正则表达式替换中文标点
        for (const [chinesePunct, englishPunct] of Object.entries(
            chineseToEnglishPunctuationMap
        )) {
            text = text.replace(new RegExp(chinesePunct, "g"), englishPunct);
        }
        $("#" + t[i] + global_content[j]).val(text);
    }
}
// ----------------------------------
// --- 复制**按钮
function Copy(language, cont, selector, name) {
    let copy = $(
        '<a id="copy" class="layui-btn fanyis" style="background-color: #bfa25b; ">' +
        name +
        "</a>"
    ).click(function () {
        let txt = $("#" + language + cont).val();
        const textarea = document.createElement("textarea");
        textarea.value = txt;
        textarea.style.position = "absolute";
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
        msgTip("【" + getLanguageName(language) + "】复制成功", 1, 1500);
    });
    $(selector).append(copy);
}

for (i = 0; i < languages.length; i++) {
    for (j = 0; j < cont.length; j++) {
        Copy(
            languages[i],
            cont[j],
            "div.a12.fanyi > div.fanyi1 > ul:nth-child(" +
            tags[i] +
            ") > li:nth-child(" +
            v[j] +
            ") > div.d1.clearfix",
            "复制" + cont_zh[j]
        );
    }
}
// ----------------------------------
// --- 复制/粘贴全部按钮功能
// 复制全部按钮功能
function CopyAll(language, selector) {
    $(selector).append(
        $(
            '<a id="copyall" class="layui-btn fanyis" style="background-color: #bfa25b; ">复制全部</a>'
        ).click(function () {
            let txt =
                $("#" + language + "title").val() +
                "\n\n" +
                $("#" + language + "content")
                    .val()
                    .replaceAll("\n", "\n\n") +
                "\n\n" +
                $("#" + language + "descript").val();
            const textarea = document.createElement("textarea");
            textarea.value = txt;
            textarea.style.position = "absolute";
            textarea.style.opacity = "0";
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand("copy");
            document.body.removeChild(textarea);
            msgTip("【" + getLanguageName(language) + "】复制成功", 1, 1500);
            dhtmlx.message("【" + getLanguageName(language) + "】复制成功");
        })
    );
}

// 粘贴全部按钮功能
function PasteAll(language, selector) {
    var zhan_tie = $(
        '<a id="pasteall" class="layui-btn fanyis" style="background-color: #bfa25b; ">粘贴全部</a>'
    ).click(function () {
        // 创建模态对话框的HTML结构
        var modalHTML =
            `
                    <div id="` +
            language +
            `PasteCustomModal" style="display: none; position: fixed; z-index: 1000; left: 50%; top: 50%; transform: translate(-50%, -50%); background: white; border: 1px solid #ccc; padding: 20px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);">
                      <textarea  id="` +
            language +
            `PasteModalTextbox" placeholder="粘贴到此处..." style="width: 100%; margin-bottom: 10px; padding: 8px; box-sizing: border-box;" />
                      </br>
                      <button id="` +
            language +
            `PasteVerifyBtn" style="margin-right: 0px; padding: 8px 16px;">确定</button>
                      <button id="` +
            language +
            `PasteClearBtn"   style="margin-right: 0px; padding: 8px 16px;">清空</button>
                      <button id="` +
            language +
            `PasteCloseBtn"   style="margin-right: 0px; padding: 8px 16px;">关闭</button>
                  </div>
                `;

        // 将模态对话框添加到页面中
        $("body").append(modalHTML);
        // 获取模态对话框和相关元素的引用
        var PasteCustomModal = $("#" + language + "PasteCustomModal");
        var PasteModalTextbox = $("#" + language + "PasteModalTextbox");
        var PasteVerifyBtn = $("#" + language + "PasteVerifyBtn");
        var PasteClearBtn = $("#" + language + "PasteClearBtn");
        var PasteCloseBtn = $("#" + language + "PasteCloseBtn");
        // 显示模态对话框
        PasteCustomModal.show();
        PasteModalTextbox.val("");
        PasteModalTextbox.focus();
        // 为确认按钮添加点击事件
        PasteVerifyBtn.on("click", function () {
            var text = PasteModalTextbox.val();
            const lines = text.split(/\r?\n/);
            // console.log(lines);
            let result = [];
            for (let i = 0; i < lines.length; i++) {
                if (lines[i] != "") result.push(lines[i]);
                else if (lines[i - 1] != "" && i > 9) result.push("*******");
            }
            // console.log(result);
            if (result.length > 6) {
                $("#" + language + "title").val(result[0]);
                $("#" + language + "content").val(result.slice(1, 6).join("\n"));
                $("#" + language + "descript").val(result.slice(7).join("\n"));
                // console.log(result.length);
                // console.log(text);
                // console.log("--------------------------");
                // for (let i = 0; i < result.length; i++) {
                //     console.log(i+":"+result[i]);
                // }
                PasteCustomModal.hide(); // 隐藏模态对话框
                msgTip("【" + getLanguageName(language) + "】粘贴成功", 1, 1500);
                dhtmlx.message("【" + getLanguageName(language) + "】粘贴成功!");
                $("#randomLineWrapping").click();
                dhtmlx.message("【随机换行】执行完成");
                $("#subheadingsCapitalized").click();
                dhtmlx.message("【小标题大写】执行完成");
            } else {
                msgTip("行数错误，标题1行，五点5行，描述最少1行！", 2, 1500);
            }
        });

        // 为清空按钮添加点击事件
        PasteClearBtn.on("click", function () {
            PasteModalTextbox.val(""); // 清空文本框内容
        });
        // 为关闭按钮添加点击事件
        PasteCloseBtn.on("click", function () {
            PasteCustomModal.hide();
        });
        // 阻止模态对话框内部的点击事件冒泡到文档（可选，但推荐）
        PasteCustomModal.on("click", function (e) {
            e.stopPropagation();
        });
    });
    $(selector).append(zhan_tie);
}

// 复制全部和粘贴全部按钮
for (i = 0; i < languages.length; i++) {
    CopyAll(
        languages[i],
        "div.a12.fanyi > div.fanyi1 > ul:nth-child(" +
        tags[i] +
        ") > li:nth-child(2) > div"
    );
    PasteAll(
        languages[i],
        "div.a12.fanyi > div.fanyi1 > ul:nth-child(" +
        tags[i] +
        ") > li:nth-child(2) > div"
    );
}

// ----------------------------------
// --- 五点：随机换行/小标题大写/emoji表情

// 五点：随机换行
let randomLineWrapping = $(
    '<a id="randomLineWrapping" class="layui-btn fanyis" style="background-color:rgba(191, 162, 91, 1)">随机换行</a>'
).click(function () {
    let lines = $("#encontent")
        .val()
        .split("\n")
        .filter(function (line) {
            return line.trim() !== "";
        });
    for (let i = lines.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [lines[i], lines[j]] = [lines[j], lines[i]];
    }
    $("#encontent").val(lines.join("\n"));
});
// 五点：小标题大写
let subheadingsCapitalized = $(
    '<a id="subheadingsCapitalized" class="layui-btn fanyis" style="background-color:rgba(191, 162, 91, 1)">小标题大写</a>'
).click(function () {
    let lines = $("#encontent").val().split("\n");
    let processedLines = lines.map(function (line) {
        let colonIndex = line.indexOf(":");
        if (colonIndex !== -1) {
            let title = line.substring(0, colonIndex).trim();
            let content = line.substring(colonIndex).trim();
            return title.toUpperCase() + content;
        }
        return line.trim();
    });
    $("#encontent").val(processedLines.join("\n"));
});
// 五点：emoji表情
let emojis = $(
    '<a id="emojis" class="layui-btn fanyis" style="background-color: rgba(191, 162, 91, 1)">表情：' +
    emoji +
    "</a>"
).click(function () {
    for (i = 0; i < languages.length; i++) {
        let lines = $("#" + languages[i] + "content")
            .val()
            .split("\n");
        if (lines[0].slice(0, emoji.length) === emoji) {
            for (let j = 0; j < lines.length; j++) {
                if (lines[j].slice(0, emoji.length) === emoji) {
                    lines[j] = lines[j].slice(emoji.length);
                }
            }
        } else if (lines[0].slice(0, emoji.length) !== emoji) {
            for (let j = 0; j < lines.length; j++) {
                if (lines[j].slice(0, emoji.length) !== emoji) {
                    lines[j] = emoji + lines[j];
                }
            }
        }
        $("#" + languages[i] + "content").val(lines.join("\n"));
    }
});
$(
    "div.a12.fanyi > div.fanyi1 > ul:nth-child(1) > li:nth-child(3) > div"
).append(randomLineWrapping, subheadingsCapitalized, emojis);
// ----------------------------------
// --- 去除H描述行前空格
function removeSpace(language) {
    $("#" + language + "descript").val(
        $("#" + language + "descript")
            .val()
            .replace(/^[\s\uFEFF\xA0]+/gm, "")
    );
}

removeSpace("en");
// ----------------------------------
// --- 去除HTML标签
$("div.a12.fanyi > div > ul:nth-child(1) > li:nth-child(4) > div").append(
    $(
        '<input type="button" class="layui-btn fanyis" style="background-color: #bfa25b; " value="去除HTML标签">'
    ).click(function () {
        $("#endescript").val(
            $("#endescript")
                .val()
                .replace(/<br\s*\/?>/gi, "\n")
                .replace(/<[^>]+>/g, "\n")
                .replace(/\n+/g, "\n")
                .trim()
        );
        removeSpace("en");
    })
);
// ----------------------------------
// --- 去除标题逗号后的空格
function removeTitleComma(languages) {
    for (i = 0; i < languages.length; i++) {
        $("#" + languages[i] + "title").val(
            $("#" + languages[i] + "title")
                .val()
                .replaceAll(", ", ",")
        );
    }
}

// 去除标题逗号后的空格
removeTitleComma(languages);

// ----------------------------------

function checkRepeatedWords(title) {
    // 常见需要忽略的介词和连词列表
    const IGNORED_WORDS = new Set([
        // 英语
        'with', 'for', 'in', 'on', 'at', 'by', 'to', 'of', 'and', 'or',
        'the', 'a', 'an', 'as', 'from', 'via', 'about', 'between', 'under',
        'through', 'but', 'because', 'if', 'when', 'although', 'while', 'since',

        // 法语
        'à', 'les', 'de', 'en', 'pour', 'avec', 'sans', 'sous', 'entre', 'et', 'mais',
        'car', 'si', 'quand', 'comme',

        // 德语
        'an', 'auf', 'bei', 'für', 'mit', 'ohne', 'über', 'zwischen', 'und',
        'aber', 'denn', 'wenn', 'obwohl', 'während',

        // 西班牙语
        'a', 'la', 'de', 'del', 'en', 'por', 'con', 'sin', 'entre', 'sobre', 'y', 'pero',
        'porque', 'si', 'cuando', 'aunque',

        // 意大利语
        'a', 'di', 'da', 'in', 'il', 'con', 'su', 'per', 'tra', 'fra', 'e', 'ma',
        'perché', 'se', 'quando', 'mentre',

        // 荷兰语
        'op', 'het', 'in', 'met', 'voor', 'tussen', 'zonder', 'bij', 'en', 'maar',
        'omdat', 'als', 'toen', 'hoewel',

        // 瑞典语
        'på', 'i', 'med', 'för', 'mellan', 'utan', 'vid', 'och', 'men',
        'eftersom', 'om', 'när', 'fastän',

        // 波兰语
        'w', 'na', 'z', 'do', 'bez', 'między', 'przez', 'i', 'ale', 'ponieważ',
        'jeśli', 'gdy', 'chociaż',

        // 其他需要忽略的词
        '|'
    ]);

    // 移除标点符号并转为小写
    const cleanedTitle = title.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '').toLowerCase();

    // 分割为单词数组
    const words = cleanedTitle.split(/\s+/);

    // 统计词频
    const wordCount = {};
    const repeatedWords = new Set();

    words.forEach(word => {
        if (word.length > 0 && !IGNORED_WORDS.has(word)) {  // 忽略空字符串和指定词
            wordCount[word] = (wordCount[word] || 0) + 1;
            if (wordCount[word] > 2) {
                repeatedWords.add(word);
            }
        }
    });

    return {
        hasRepeatedWords: repeatedWords.size > 0,
        repeatedWords: Array.from(repeatedWords),
        wordFrequency: wordCount
    };
}


// 示例用法
// const result = checkRepeatedWords("Wireless Bluetooth Headphones, Wireless Headphones with Mic, Wireless Charging");
// console.log(result);

// --- 检查异常按钮
let checkAnomalies = $(
    '<a id="check-bt" class="layui-btn" style="background-color: rgba(191, 162, 91, 0.7); position: fixed; margin-left: 180px; bottom: 10px;">' +
    '<img src="https://cn.bing.com/sa/simg/favicon-trans-bg-blue-mg.ico" alt="" style="width:20px"> 检查异常</a>'
).click(function () {
    scrollTo(0, 10000);
    const checkLanguages = ["en", "fr", "de", "it", "es", "nl", "sv", "pl"];
    const checkLanguagesCN = [
        "英&nbsp&nbsp语",
        "法&nbsp&nbsp&nbsp语",
        "德&nbsp&nbsp语",
        "意大利",
        "西班牙",
        "荷&nbsp&nbsp兰",
        "瑞&nbsp&nbsp典",
        "波&nbsp&nbsp兰",
    ];
    let tipsTable =
        '<table style="width: 100%; text-align: center; padding: 10px" border="1"><tr><th>语言</th><th>异常类型</th><th>详细信息</th></tr>';
    for (i = 0; i < checkLanguages.length; i++) {
        let language = checkLanguages[i];
        let langName = checkLanguagesCN[i];
        // 标题检查
        let title = $("#" + language + "title");
        console.log(title.val())
        const result = checkRepeatedWords(title.val());
        console.log(result);
        let titleLength = title.val().length;
        let titleTip = "";
        let table = document.querySelector("#variant-price-table tbody");
        let maxLength = Array.from(table.rows).reduce((max, row) => {
            let variantText = row.cells[1].innerText.trim().replace(/<.*?>/g, "");
            return Math.max(max, variantText.length);
        }, 0);
        if (titleLength === 0) {
            titleTip = "【标题未填：" + titleLength + "】";
        } else if (titleLength < 90) {
            titleTip = "【标题短缺：" + titleLength + "】";
        } else if (titleLength > 200) {
            titleTip = "【标题超出：" + titleLength + "】";
        } else if (maxLength > 0) {
                let recommendedMaxLength = 200 - maxLength - titleLength - 2;
                console.log('%c [ recommendedMaxLength ]-1152', 'font-size:13px; background:pink; color:#bf2c9f;', recommendedMaxLength)
                if (titleLength + maxLength + 2 > 200) {

                    titleTip =
                        "【标题可能超出，变体：" +
                        maxLength +
                        "，标题：" +
                        titleLength +
                        "，建议长度：" +
                        recommendedMaxLength +
                        "】";
                }
                console.log('123', titleLength + maxLength + 2)
        } else if (result["hasRepeatedWords"]) {
            titleTip = "【字词重复：" + result["repeatedWords"].join(", ") + "】";
        }
        if (titleTip) {
            tipsTable +=
                "<tr><td>" +
                langName +
                "</td><td style='background-color: aqua'>标题异常</td><td>" +
                titleTip +
                "</td></tr>";
        }
        // 关键词检查
        let keyword = document.getElementById(language + "keyword");
        if (keyword) {
            keyword.value = keyword.value.replaceAll(",", "").replaceAll(".", "");
            let keywordLength = keyword.value.length;
            if (keywordLength > 250) {
                tipsTable +=
                    "<tr><td>" +
                    langName +
                    "</td><td style='background-color: chartreuse'>关键词异常</td><td>【关键词超出字符：" +
                    keywordLength +
                    "】</td></tr>";
            }
        }

        // 五点检查
        let content = document.getElementById(language + "content");
        if (content) {
            let textArray = content.value.split("\n");
            let pointTips = "";
            if (textArray.length !== 5) {
                pointTips = "【五点数量异常：" + textArray.length + "】";
            } else {
                for (let j = 0; j < textArray.length; j++) {
                    let m = j + 1;
                    let pointLength = textArray[j].length;
                    if (pointLength > 500 || pointLength < 60) {
                        pointTips += "【第 " + m + " 点异常：" + pointLength + "】<br>";
                    }
                }
            }
            if (pointTips) {
                tipsTable +=
                    "<tr><td>" +
                    langName +
                    "</td><td style='background-color: rgba(201,142,255,0.55)'>五点异常</td><td>" +
                    pointTips +
                    "</td></tr>";
            }
        }

        // 描述检查
        let descript = document.getElementById(language + "descript");
        if (descript) {
            let descLength = descript.value.length;
            if (descLength === 0 || descLength > 1900) {
                tipsTable +=
                    "<tr><td>" +
                    langName +
                    "</td><td style='background-color: rgba(159,226,255,0.57)'>描述异常</td><td>【描述异常：" +
                    descLength +
                    "】</td></tr>";
            }
        }
    }
    // 变体售价检查
    let rows = document.querySelectorAll("#variant-price-table > tbody > tr");
    rows.forEach(function (row) {
        let priceInput = row.querySelector(".bt_price");
        if (priceInput) {
            let price = parseFloat(priceInput.value);
            if (price === 0) {
                let variant = row.querySelector("td:nth-child(2)").textContent.trim();
                tipsTable +=
                    "<tr><td>变体</td><td>售价异常</td><td>【" +
                    variant +
                    "：" +
                    price +
                    "】</td></tr>";
            }
        }
    });
    // 主体售价检查
    let bt_table = document.querySelector("#variant-price-table > tbody");
    let chengben = $("#chengben").val();
    let zhongliang = $("#zhongliang").val();
    let uk_yuanfei = $(
        "#yunfei > tbody > tr:nth-child(4) > td:nth-child(6) > input[type=text]"
    ).val();
    if (
        !bt_table.firstElementChild &&
        chengben === "100.00" &&
        zhongliang === "5" &&
        uk_yuanfei === "276.0"
    ) {
        tipsTable +=
            '<tr><td colspan="3" style="text-align: center">成本：【售价异常】</td></tr>';
    }

    tipsTable += "</table>";
    if (
        tipsTable ===
        '<table style="width: 100%; text-align: center; padding: 10px" border="1"><tr><th>语言</th><th>异常类型</th><th>详细信息</th></tr></table>'
    ) {
        msgTip("无异常", 6, 1500);
    } else {
        let modalHTML = `
                    <div id="TipsModal" style="display: none; position: fixed; z-index: 1000; left: 50%; top: 50%; transform: translate(-50%, -50%); background: white; border: 1px solid #ccc; padding: 20px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);">
                        ${tipsTable}
                        <button id="TipsConfirmBtn" style="margin-right: 0px; padding: 8px 16px;width: 100%;">确定</button>
                    </div>
                `;

        $("body").append(modalHTML);
        let TipsModal = $("#TipsModal");
        TipsModal.show();
        let TipsConfirmBtn = $("#TipsConfirmBtn");
        TipsConfirmBtn.on("click", function () {
            TipsModal.hide();
        });
    }
});
$(".layui-btn.b1.fl").after(checkAnomalies);

// ----------------------------------
// --- 翻译区输入框内容和value实时更新
// 给input和textarea添加实时更新value
function changeValue(obj) {
    $(obj).attr("value", $(obj).val());
}

// 等待DOM加载完成
document.addEventListener("DOMContentLoaded", function () {
    // 查找目标容器
    const container = document.querySelector("div.a12.fanyi > div.fanyi1");
    if (container) {
        // 获取容器内所有input和textarea元素
        const elements = container.querySelectorAll("input, textarea");
        // 遍历所有元素并添加onchange属性
        elements.forEach((element) => {
            element.setAttribute("onchange", "changeValue(this)");
        });
    } else {
        console.error("错误：未找到目标容器元素");
    }
});

// 更新ul标签国家和字符数方法
function updateCountryNumber(countryName, newNumber) {
    // 获取目标<ul>元素
    const ulElement = document.querySelector(
        "body > div.x-body > div > form > div > div.a12.fanyi > ul"
    );

    if (!ulElement) {
        console.error("未找到语言列表容器");
        return false;
    }

    // 获取所有<li>元素
    const listItems = ulElement.querySelectorAll("li");
    let isUpdated = false;

    // 遍历所有列表项
    listItems.forEach((li) => {
        const link = li.querySelector("a");
        if (link) {
            // 分割文本内容（示例："波兰 - 195"）
            const parts = link.textContent.split(" - ");

            // 匹配国家名称（去除首尾空格）
            if (parts[0].trim() === countryName.trim()) {
                // 更新数字并保持原有格式
                link.textContent = `${countryName} - ${newNumber}`;
                isUpdated = true;

                // 可选：高亮更新效果
                link.style.transition = "none";
                link.style.color = "#24ea00";
                setTimeout(() => {
                    link.style.color = "";
                }, 50);
            }
        }
    });

    if (!isUpdated) {
        console.warn(`未找到指定国家：${countryName}`);
        return false;
    }
    return true;
}

// 给标题输入框加实时检测字符数，并调用【更新ul标签国家和字符数方法】
for (let i = 0; i < languages.length; i++) {
    const input_dom = document.getElementById(languages[i] + "title");
    input_dom.addEventListener("input", function (event) {
        const value = event.target.value; // 获取输入的值
        updateCountryNumber(languages_zh[i], value.length);
    });
}

function encodeSpecialChars(text) {
    const specialCharsMap = {
        " ": "%20",
        '"': "%22",
        "#": "%23",
        "%": "%25",
        "&": "%26",
        "(": "%28",
        ")": "%29",
        "+": "%2B",
        ",": "%2C",
        "/": "%2F",
        ":": "%3A",
        ";": "%3B",
        "<": "%3C",
        "=": "%3D",
        ">": "%3E",
        "?": "%3F",
        "@": "%40",
        "\\": "%5C",
        "|": "%7C",
        "~": "%7E",
        "`": "%60",
        "[": "%5B",
        "]": "%5D",
        "!": "%21",
        $: "%24",
        "{": "%7B",
        "}": "%7D",
        "^": "%5E",
        "*": "%2A",
        "'": "%27",
    };

    let encodedText = "";

    for (let i = 0; i < text.length; i++) {
        const char = text[i];
        encodedText += specialCharsMap[char] || char; // 如果字符在映射表中，使用映射值；否则，保留原字符
    }

    return encodedText;
}

// URL编码
function customURLEncode(str) {
    // 定义完整的特殊字符映射表（修正版）
    const encodeMap = {
        " ": "%20",
        '"': "%22",
        "#": "%23",
        "%": "%25",
        "&": "%26",
        "(": "%28",
        ")": "%29",
        "+": "%2B",
        ",": "%2C",
        "/": "%2F",
        ":": "%3A",
        ";": "%3B",
        "<": "%3C",
        "=": "%3D",
        ">": "%3E",
        "?": "%3F",
        "@": "%40",
        "\\": "%5C",
        "|": "%7C",
        "~": "%7E",
        "`": "%60",
        "[": "%5B",
        "]": "%5D",
        "!": "%21",
        $: "%24",
        "{": "%7B",
        "}": "%7D",
        "^": "%5E",
        "*": "%2A",
        "'": "%27",
        "\n": "%0A",
    };
    // 创建匹配所有特殊字符的正则表达式
    const regex = new RegExp(
        `[${Object.keys(encodeMap)
            .map(
                (c) =>
                    // 对正则特殊字符进行转义处理
                    c.replace(/[\\\]^]/g, "\\$&") // 转义 \、]、^ 等字符
            )
            .join("")}]`,
        "g"
    );
    // 执行批量替换
    return str.replace(regex, (match) => encodeMap[match]);
}

//获取谷歌翻译按钮
function OpenGoogleTranslate(selector) {
    const OpenTranslate = $(
        '<a id="OpenTranslate" class="layui-btn" style="background-color: rgba(255, 255, 255, 0.7); color: #4285F4;border: 1px solid #808080; position: fixed; margin-left: 330px; bottom: 10px;"><img src="https://www.gstatic.com/translate/favicon.ico" alt="" style="width:20px"> 获取谷歌翻译</a>'
    ).click(function () {
        let title = customURLEncode($("#entitle").val());
        let content = customURLEncode(
            $("#encontent").val().replaceAll("\n", "\n\n")
        );
        let descript = customURLEncode($("#endescript").val());
        // console.log(title)
        console.log(content);
        console.log(descript);

        let language = ["fr", "de", "it", "es", "nl", "sv", "pl"];
        // let language = ["fr"]
        for (let i = 0; i < language.length; i++) {
            let title_url =
                "https://translate.google.com/?hl=zh-CN&sl=auto&tl=" +
                language[i] +
                "&text=" +
                title +
                "&op=translate" +
                "#id=" +
                getUrlParam("id") +
                "&type=title";
            console.log(title_url);
            window.open(title_url, "_blank");

            let content_url =
                "https://translate.google.com/?hl=zh-CN&sl=auto&tl=" +
                language[i] +
                "&text=" +
                content +
                "&op=translate" +
                "#id=" +
                getUrlParam("id") +
                "&type=content";
            console.log(content_url);
            window.open(content_url, "_blank");

            let descript_url =
                "https://translate.google.com/?hl=zh-CN&sl=auto&tl=" +
                language[i] +
                "&text=" +
                descript +
                "&op=translate" +
                "#id=" +
                getUrlParam("id") +
                "&type=descript";
            console.log(descript_url);
            window.open(descript_url, "_blank");
        }
    });
    // $(selector).append(OpenTranslate);
    $(selector).after(OpenTranslate);
}

//填入谷歌翻译按钮
function PasteGoogleTranslate(selector) {
    var PasteTranslate = $(
        '<a id="PasteTranslate" class="layui-btn " style="background-color: rgba(255, 255, 255, 0.7); color: #4285F4;border: 1px solid #808080; position: fixed; margin-left: 500px; bottom: 10px;"><img src="https://www.gstatic.com/translate/favicon.ico" alt="" style="width:20px"> 填入谷歌翻译</a>'
    ).click(function () {
        const id = getUrlParam("id");
        console.log(id);
        const url = "http://127.0.0.1:10086/translate/get/" + id;
        console.log(url);
        const l = ["fr", "de", "it", "es", "nl", "sv", "pl"];
        // 方式二
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        // xhr.withCredentials = true; // 如果需要的话

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = JSON.parse(xhr.responseText);

                if (data.countries.fr) {
                    $("#frtitle").val(data.countries.fr.title);
                    $("#frcontent").val(data.countries.fr.content);
                    $("#frdescript").val(data.countries.fr.descript);
                    dhtmlx.message(getLanguageName("fr") + "填入完成！");
                }

                if (data.countries.de) {
                    $("#detitle").val(data.countries.de.title);
                    $("#decontent").val(data.countries.de.content);
                    $("#dedescript").val(data.countries.de.descript);
                    dhtmlx.message(getLanguageName("de") + "填入完成！");
                }

                if (data.countries.it) {
                    $("#ittitle").val(data.countries.it.title);
                    $("#itcontent").val(data.countries.it.content);
                    $("#itdescript").val(data.countries.it.descript);
                    dhtmlx.message(getLanguageName("it") + "填入完成！");
                }
                if (data.countries.es) {
                    $("#estitle").val(data.countries.es.title);
                    $("#escontent").val(data.countries.es.content);
                    $("#esdescript").val(data.countries.es.descript);
                    dhtmlx.message(getLanguageName("es") + "填入完成！");
                }
                if (data.countries.nl) {
                    $("#nltitle").val(data.countries.nl.title);
                    $("#nlcontent").val(data.countries.nl.content);
                    $("#nldescript").val(data.countries.nl.descript);
                    dhtmlx.message(getLanguageName("nl") + "填入完成！");
                }
                if (data.countries.sv) {
                    $("#svtitle").val(data.countries.sv.title);
                    $("#svcontent").val(data.countries.sv.content);
                    $("#svdescript").val(data.countries.sv.descript);
                    dhtmlx.message(getLanguageName("sv") + "填入完成！");
                }
                if (data.countries.pl) {
                    $("#pltitle").val(data.countries.pl.title);
                    $("#plcontent").val(data.countries.pl.content);
                    $("#pldescript").val(data.countries.pl.descript);
                    dhtmlx.message(getLanguageName("pl") + "填入完成！");
                }

                $("#ustitle").val($("#entitle").val());
                $("#uscontent").val($("#encontent").val());
                $("#usdescript").val($("#endescript").val());
                dhtmlx.message(getLanguageName("us") + "填入完成！");

                setTimeout(function () {
                    $(".layui-btn.b1.fl").click();
                }, 500);

                // console.log(data.countries.fr);
            } else if (xhr.status === 404) msgTip("未发现该id的翻译内容！", 5, 1500);
        };

        xhr.send();
    });
    // $(selector).append(PasteTranslate);
    $(selector).after(PasteTranslate);
}

//填入谷歌翻译按钮
function GetTranslate(selector) {
    var GetTranslate = $(
        '<a id="GetTranslate" class="layui-btn " style="background-color: rgba(255, 255, 255, 0.7); color: #4285F4;border: 1px solid #808080; position: fixed; margin-left: 670px; bottom: 10px;"><img src="https://www.gstatic.com/translate/favicon.ico" alt="" style="width:20px"> 谷歌翻译</a>'
    ).click(function () {
        const id = getUrlParam("id");
        console.log(id);
        const url = "http://127.0.0.1:10086/translate/api";
        console.log(url);
        let data = {
            id: id,
            title: customURLEncode($("#entitle").val()),
            content: customURLEncode($("#encontent").val()),
            descript: customURLEncode($("#endescript").val()),
        };
        var xhr = new XMLHttpRequest();
        xhr.open("POST", url, true);
        // 设置 JSON 请求头
        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    console.log("成功:", xhr.responseText);
                } else {
                    console.error("错误:", xhr.status);
                }
            }
        };

        // 发送 JSON 字符串
        var jsonData = JSON.stringify(data);
        xhr.send(jsonData);

        // const l = ["fr", "de", "it", "es", "nl", "sv", "pl"]
        // // 方式二
        // var xhr = new XMLHttpRequest();
        // xhr.open('GET', url, true);
        // // xhr.withCredentials = true; // 如果需要的话
        //
        // xhr.onreadystatechange = function () {
        //     if (xhr.readyState === 4 && xhr.status === 200) {
        //         let data = JSON.parse(xhr.responseText)
        //
        //         $("#frtitle").val(data.countries.fr.title)
        //         $("#frcontent").val(data.countries.fr.content)
        //         $("#frdescript").val(data.countries.fr.descript)
        //         dhtmlx.message(getLanguageName("fr") + "填入完成！")
        //
        //         $("#detitle").val(data.countries.de.title)
        //         $("#decontent").val(data.countries.de.content)
        //         $("#dedescript").val(data.countries.de.descript)
        //         dhtmlx.message(getLanguageName("de") + "填入完成！")
        //
        //         $("#ittitle").val(data.countries.it.title)
        //         $("#itcontent").val(data.countries.it.content)
        //         $("#itdescript").val(data.countries.it.descript)
        //         dhtmlx.message(getLanguageName("it") + "填入完成！")
        //
        //         $("#estitle").val(data.countries.es.title)
        //         $("#escontent").val(data.countries.es.content)
        //         $("#esdescript").val(data.countries.es.descript)
        //         dhtmlx.message(getLanguageName("es") + "填入完成！")
        //
        //         $("#nltitle").val(data.countries.nl.title)
        //         $("#nlcontent").val(data.countries.nl.content)
        //         $("#nldescript").val(data.countries.nl.descript)
        //         dhtmlx.message(getLanguageName("nl") + "填入完成！")
        //
        //         $("#svtitle").val(data.countries.sv.title)
        //         $("#svcontent").val(data.countries.sv.content)
        //         $("#svdescript").val(data.countries.sv.descript)
        //         dhtmlx.message(getLanguageName("sv") + "填入完成！")
        //
        //         $("#pltitle").val(data.countries.pl.title)
        //         $("#plcontent").val(data.countries.pl.content)
        //         $("#pldescript").val(data.countries.pl.descript)
        //         dhtmlx.message(getLanguageName("pl") + "填入完成！")
        //
        //         $("#ustitle").val($("#entitle").val())
        //         $("#uscontent").val($("#encontent").val())
        //         $("#usdescript").val( $("#endescript").val())
        //         dhtmlx.message(getLanguageName("us") + "填入完成！")
        //
        //
        //         setTimeout(function () {
        //             $(".layui-btn.b1.fl").click();
        //         }, 500);
        //
        //         // console.log(data.countries.fr);
        //     } else if (xhr.status === 404) msgTip("未发现该id的翻译内容！", 5, 1500)
        // };
        //
        // xhr.send();
    });
    // $(selector).append(PasteTranslate);
    $(selector).after(GetTranslate);
}

//获取翻译
GetTranslate($("#check-bt"));
//粘贴谷歌翻译
PasteGoogleTranslate($("#check-bt"));
//打开谷歌翻译
OpenGoogleTranslate($("#check-bt"));


setDefaultPrice();
clickComputePrice();


// const crypto = require('crypto');

// function generateApiKey(apisecret, apicode, apitimes) {

//   const rawString = apisecret + apicode + apitimes;
//   return crypto.createHash('md5').update(rawString).digest('hex');
// }

// // 示例使用
// const apisecret = "wb0c7mprr2xp";
// const apicode = "eg1659";
// const apitimes = "1747472933";

// // wb0c7mprr2xpeg16591747472933
// const apiKey = generateApiKey(apisecret, apicode, apitimes);
// console.log(apiKey); // 输出: bbe6140b3bf70e0d047320be1f61a963


// window.onload = function () {
//     // 这里可以执行一些初始化代码
//     console.log("页面加载完成");

//     // 使用浏览器原生Crypto API实现
//     async function generateApiKey(apisecret, apicode, apitimes) {
//         const rawString = apisecret + apicode + apitimes;
//         const msgBuffer = new TextEncoder().encode(rawString);
//         const hashBuffer = await crypto.subtle.digest('MD5', msgBuffer);
//         const hashArray = Array.from(new Uint8Array(hashBuffer));
//         return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
//     }

//     // 示例调用
//     (async () => {
//         const apisecret = "wb0c7mprr2xp";
//         const apicode = "eg1659";
//         const apitimes = "1747472933";

//         const apiKey = await generateApiKey(apisecret + apicode + apitimes);
//         console.log(apiKey); // 输出: bbe6140b3bf70e0d047320be1f61a963
//     })();
// };
